<?php

namespace App\Services;

use App\Models\CompanyUser;
use App\Models\Menu;
use App\Models\Role;

class RuleMenuService extends BaseService
{
    /**
     * 获取菜单列表并组装好结构 （当前登录人员所具备的权限）
     * 他给角色分配的权限，不应超过自己拥有的权限
     */
    public function treeMenus()
    {
        $ruleMenus = get_user_rule_menus();
        if (empty($ruleMenus)) {
            $ruleMenus = $this->leftMenus();
        }

        return $ruleMenus;
    }

    /**
     * 树形菜单，用户对应角色拥有的
     *
     * @return array
     * @author: lxk
     * @date: 2025-03-27 16:20
     */
    public function leftMenus() : array
    {
        $ruleMenus = $this->getMenuArray();
        foreach ($ruleMenus as &$val) {
            $val['icon_tmp'] = $val['icon'];
        }

        return $this->formatMenus($ruleMenus);
    }

    /**
     * 获取用户当前的用户的权限菜单，纯二维数组
     *
     * @return array
     * @author: lxk
     * @date: 2025-03-27 16:19
     */
    public static function getMenuArray() : array
    {
        $userId = user_id();
        if (is_super_admin()) {
            $roleId = 1;
        } else {
            $roleId = CompanyUser::query() //当前用户角色
                ->where('user_id', $userId)
                ->where('company_id', company_id())
                ->value('role_id');
        }
        $menuIds = Role::query()->where('id', $roleId)->value('menu_ids');
        if (empty($menuIds)) return [];

        $menuIds = to_array($menuIds);

        return  Menu::query() //查找权限
            ->whereIn('id', $menuIds)
            ->select(['id', 'title', 'parent_id', 'icon', 'icon_active', 'is_menu', 'url', 'sort'])
            ->where('status', 1)
            ->where('is_menu', 1)
            ->orderBy('sort')
            ->orderBy('id')
            ->get()
            ->toArray();
    }

    /**
     * 格式化返回数据
     */
    public function formatMenus($ruleMenus)
    {
        $ruleMenus = $this->getTree($ruleMenus);

        cache_user_rule_menus($ruleMenus);

        return $ruleMenus;
    }

    /**
     * 获取子树
     */
    public function getTree($array, $id = 0)
    {
        $tree = array();
        foreach ($array as $value) {
            if (in_array($id, explode(',', $value['parent_id']))) {
                $value['children'] = $this->getTree($array, $value['id']);
                if (!$value['children']) {
                    unset($value['children']);
                }
                $tree[] = $value;
            }
        }

        return $tree;
    }

}
